require 'family_tree_api/search/person'

module FamilyTreeApi
  module Search
    class Result
      attr_accessor :ref, :score, :person, :parents, :spouses, :children

      def father
        @father ||= @parents.select{|p| p.role == "Father"}.first
        @father
      end

      def mother
        @mother ||= @parents.select{|p| p.role == "Mother"}.first
        @mother
      end

      def self.parse(r_element)
        result = self.new
        result.ref = r_element.attributes["ref"]
        r_element.each do |e|
          case e.name
          when 'score'
            result.score = e.content
          when 'person'
            result.person = Search::Person.parse(e)
          when 'parents'
            result.parents = e.children.collect do |p|
              Parent.parse(p)
            end
          when 'spouses'
            result.spouses = e.children.collect do |s|
              Person.parse(s)
            end
          when 'children'
            result.children = e.children.collect do |c|
              Person.parse(c)
            end
          end
        end
        result
      end
    end

  end
end